package cn.tx.erp.sys.service.impl;

import cn.tx.erp.sys.domain.Role;
import cn.tx.erp.sys.mapper.RoleMapper;
import cn.tx.erp.sys.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/7/11 18:10
 */
@Service
//@Transactional // 事务
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 重写删除的方法
     * @param id
     * @return
     */
    @Override
    public boolean removeById(Serializable id) {
        //根据角色id删除 sys_role_permission
        this.getBaseMapper().deleteRolePermissionByRid(id);
        // 根据角色id 删除 sys_role_user
        this.getBaseMapper().deleteRoleUserByRid(id);
        return super.removeById(id);
    }

    /**
     * 根据角色id 查询 权限或菜单id 集合
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> queryRolePermissionByRid(Integer roleId) {
        return this.getBaseMapper().queryRolePermissionByRid(roleId);
    }

    /**
     * 保存角色和菜单权限之间的关系
     * @param rid
     * @param ids
     */
    @Override
    public void saveRolePermission(Integer rid, Integer[] ids) {
        // 拿到roleMapper
        RoleMapper roleMapper = this.getBaseMapper();
        // 清空数据，重新插入
        roleMapper.deleteRolePermissionByRid(rid);
        //
        if (ids != null && ids.length > 0) {
            for (Integer pid : ids) {
                roleMapper.saveRolePermission(rid, pid);
            }
        }

    }

    /**
     * 查询当前用户所 拥有的角色 id 集合
     * @param id
     * @return
     */
    @Override
    public List<Integer> queryUserRoleIdsByUid(Integer id) {
        return roleMapper.queryUserRoleByUid(id);
    }
}
